<template>
	<view>
		<uni-forms ref="form" :modelValue="formData" :rules="rules">
			<uni-forms-item label="名称" name="name">
				<uni-easyinput type="text" v-model="formData.name" placeholder="分类名" />
			</uni-forms-item>
			<uni-forms-item label="价格" name="price">
				<uni-easyinput type="number" @input="priceInput"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item label="分类图" name="img">
				<u-upload 
					:fileList="classItemImgBase.length > 0 ? classItemImgBase:value " 
					:maxCount="1" 
					@afterRead="onImageLoad"
					@delete="onImageDelect"
					>
				</u-upload>
			</uni-forms-item>
		</uni-forms>
	</view>
</template>

<script>
	import { uploadImg } from '@/tools/upload.js'
	export default {
		name:"AddClassifyItem",
		data() {
			return {
				// 表单数据
				formData: {
					name: '',
					price:0,
					img:''
				},
				classItemImgBase:[],
				rules: {
					// 对name字段进行必填验证
					name: {
						rules: [{
								required: true,
								errorMessage: '请输入标题',
							},
							{
								minLength: 2,
								maxLength: 20,
								errorMessage: '长度在 {minLength} 到 {maxLength} 个字符',
							}
						]
					},
					price:{
						rules:[
							{
								required:true,
								errorMessage: '请输入价格',
							},
							{
								validateFunction:(_1,value,_2,_3)=>{
									if (value >= 0 ){
										return true
									}else{
										return false
									}
								},
								errorMessage:"价格必须大于等于0"
							}
						]
					},
					img:{
						rules:[
							{
								validateFunction:(_1,value,_2,callback)=>{
									if (this.classItemImgBase[0]) {
										if (this.classItemImgBase[0].status){
											return false
										}
									}
									return true
								},
								errorMessage: '图片上传中'
							}
						]
					}
				}
			}
		},
		methods: {
			submit() {
				return this.$refs.form.validate()
			},
			onImageDelect(){
				this.classItemImgBase = []
			},
			priceInput(value){
				this.formData.price = Number(value)
			},
			async onImageLoad({file}){
				const { url } = file
				this.classItemImgBase = [{
					...file,
					status: 'uploading',
					message: '上传中'
				}]
				try{
				const imgUrl = await uploadImg(url) 
				this.classItemImgBase = [
					{url:imgUrl}
				]
				this.formData.img = imgUrl
				}catch{
					uni.showToast({
						title:"图片上传失败,请稍后重试",
						icon:'error'
					})
				}
			}
			
		},
		props:["value"]
	}
</script>

<style lang="scss">

</style>
